'use strict'
var HistoryModel = require('../../model/history');
var FinanceModel = require('../../model/finance');
var Data = require('../../util/data')

class History {
    async getAll(req, res, next) {
        try {
            const histories = await HistoryModel.find({});
            res.send(histories);
        } catch (err) {
            res.send(Data.throwError('获取资金数据失败'))
        }
    }
    async get(req, res, next) {
        try {
            const id = req.params.id
            const history = await HistoryModel.findOne({ '_id': id });
            res.send(history);
        } catch (err) {
            res.send(Data.throwError('获取资金数据失败'))
        }
    }
    async getByFinanceId(req, res, next) {
        try {
            const financeId = req.params.financeId
            const histories = await HistoryModel.find({ financeId });
            res.send(histories);
        } catch (err) {
            res.send(Data.throwError('获取资金数据失败'))
        }
    }
    async post(req, res, next) {
        try {
            const item = req.body
            const financeId = item.financeId
            const histories = await HistoryModel.insertMany(item);
            const history = histories[0]
            const finance = await FinanceModel.findOne({ _id: financeId })
            finance.remain = history.remain
            await FinanceModel.update({ _id: financeId }, finance)
            res.send(history);
        } catch (err) {
            res.send(Data.throwError('创建资金数据失败'))
        }
    }
    async delete(req, res, next) {
        try {
            const id = req.params.id
            const history = await HistoryModel.deleteOne({ _id: id });
            res.send(history);
        } catch (err) {
            res.send(Data.throwError('删除资金数据失败'))
        }
    }
    async put(req, res, next) {
        try {
            const id = req.params.id
            const data = req.body
            const history = await HistoryModel.update({ _id: id }, data);
            res.send(history);
        } catch (err) {
            res.send(Data.throwError('修改资金数据失败'))
        }
    }
}

module.exports = new History()